/**
 * 负责创建房间后在局域网内广播房间信息
 */
#include "network.h"
#include <stdio.h>
#include <string.h>
#include <winsock2.h>
#include "tinycthread.h"
#include "procedure.h"

#pragma comment(lib, "ws2_32.lib")

int broadCastIpCount = 0;
char broadCastIps[10][64];
bool broadCastOn = false;
SOCKET broadcastSocket;

void initBroadcast() {
    int commaCount;
    char **ips = localIps;
    char *si,*di;
    while(*ips != NULL && broadCastIpCount < 10) {
        commaCount = 0;
        si = *ips;
        di = broadCastIps[broadCastIpCount];
        while(*si) { //将本地ip的最后一个逗号后面的部分改为255
            if(commaCount < 3) {
                *di = *si;
                di++;
                si++;
            } else {
                di[0] = '.';
                di[1] = '2';
                di[2] = '5';
                di[3] = '5';
                di[4] = 0;
                break;
            }
            if (*si == '.')
            {
                commaCount++;
            }
            
        }
        broadCastIpCount++;
        ips++;
    }
    printf("检测到你的局域网段ip：\n");
    for (size_t i = 0; i < broadCastIpCount; i++)
    {
        printf("  %s\n",broadCastIps[i]);
    }
    
}

int asyncBroadcast(void *args)
{
    struct sockaddr_in broadcastAddr;
    char buffer[64];
    puts("Start broadcasting");
    while(broadCastOn) {
        GenerateLocalRoomInfo(buffer);
        for (size_t i = 0; i < broadCastIpCount; i++) {
            memset(&broadcastAddr, 0, sizeof(broadcastAddr));
            broadcastAddr.sin_family = AF_INET;
            broadcastAddr.sin_addr.s_addr = inet_addr(broadCastIps[i]);
            broadcastAddr.sin_port = htons(PORT);
            if (sendto(broadcastSocket, buffer, strlen(buffer), 0, (struct sockaddr*)&broadcastAddr, sizeof(broadcastAddr)) == SOCKET_ERROR) {
                printf("Failed to send broadcast message\n");
                closesocket(broadcastSocket);
                return 1;
            }
        }
        Sleep(3000);
    }
    closesocket(broadcastSocket);
    printf("UDP广播已关闭\n");
    return 0;
}

bool StartBroadcast() 
{
    initBroadcast();
    // 创建UDP socket
    if ((broadcastSocket = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET) {
        printf("Failed to create socket\n");
        return false;
    }

    // 设置广播选项
    int broadcastOption = 1;
    if (setsockopt(broadcastSocket, SOL_SOCKET, SO_BROADCAST, (char*)&broadcastOption, sizeof(broadcastOption)) == SOCKET_ERROR) {
        printf("Failed to set broadcast option\n");
        closesocket(broadcastSocket);
        return false;
    }
    broadCastOn = true;
    thrd_t caster;
    thrd_create(&caster,asyncBroadcast,NULL);
    return true;
}

void StopBroadcast() 
{
    broadCastIpCount = 0;
    broadCastOn = false;
}